package controller;

import common.Result;
import entity.User;
import entity.Students;
import service.UserService;
import service.StudentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import dto.RegisterDTO;
import org.springframework.http.ResponseEntity;
//@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StudentsService studentsService;

    @GetMapping("/{id}")
    public User getById(@PathVariable Integer id) {
        return userService.getById(id);
    }

    @GetMapping("/all")
    public List<User> getAll() {
        return userService.getAll();
    }

    @PostMapping
    public int create(@RequestBody User obj) {
        return userService.create(obj);
    }

    @PutMapping
    public int update(@RequestBody User obj) {
        return userService.update(obj);
    }

    @DeleteMapping("/{id}")
    public int delete(@PathVariable Integer id) {
        return userService.delete(id);
    }

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody RegisterDTO dto) {
        try {
            userService.register(dto);
            return ResponseEntity.ok("注册成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body("参数错误：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace(); // 可加日志
            return ResponseEntity.status(500).body("服务器异常：" + e.getMessage());
        }
    }
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> loginInfo) {
        System.out.println("收到登录请求，参数：" + loginInfo);
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");
        String role = loginInfo.get("role");

        User user = userService.findByUsername(username);
        if (user == null) {
            return Result.error("用户不存在", 401);
        }

        if (!user.getPassword().equals(password)) {
            return Result.error("密码错误", 401);
        }

        if ("admin".equals(role) && user.getUserType() != 2) {
            return Result.error("该用户不是管理员", 403);
        }

        if ("student".equals(role) && user.getUserType() != 0) {
            return Result.error("该用户不是学生", 403);
        }

        // 登录成功，返回用户信息
        Map<String, Object> data = new HashMap<>();
        data.put("userId", user.getUserId());
        data.put("username", user.getUsername());
        data.put("role", role);

        // 如果是学生登录，还需要返回学生详细信息
        if ("student".equals(role)) {
            Students student = studentsService.getByUserId(user.getUserId());
            if (student != null) {
                data.put("studentId", student.getStudentId());
                data.put("name", student.getName());
                data.put("gender", student.getGender());
                data.put("college", student.getCollege());
                data.put("department", student.getDepartment());
                data.put("gradeYear", student.getGradeYear());
                data.put("status", student.getStatus());
            }
        }

        return Result.success("登录成功", data);
    }

}